//
//  UIImageView+myImage.m
//  10- 21 网络请求 本地缓存封装
//
//  Created by weidawei on 14-10-21.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "UIImageView+myImage.h"
#import "OtherCell2.h"

@interface UIImageView ()
@property (nonatomic, retain) OtherCell2 * cell;

@end

@implementation UIImageView (myImage)



- (void)setImageWithUrlStr:(NSString *)str
{
    
    // 全局队列加载数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        // 拼接地址
        
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        // 图片的地址
        NSString * iamgPath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%u.bbb", [str hash]]];
        
        NSData *data = [NSKeyedUnarchiver unarchiveObjectWithFile:iamgPath];
        
        UIImage *iamge = nil;
        
        if (data == nil) {
            
            // 加载本地没有数据,直接利用一个同步方法,从网络下载
            NSString *strUrl = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url =[NSURL URLWithString:strUrl];
            
            
            
            
            
            //加载同步方法
            NSData *imageData = [NSData dataWithContentsOfURL:url];
            
            
            //将从网络获取的数据写入本地
            BOOL result = [NSKeyedArchiver archiveRootObject:imageData toFile:iamgPath];
            NSLog(@"图片写入结果 : %d",result);
            
            
            
            iamge = [UIImage imageWithData:imageData];
            
            // 加载完成,返回主线程刷新UI视图
            dispatch_async(dispatch_get_main_queue(), ^{
               
                self.image = iamge;
                
//                self.cell.label2.textColor = [UIColor whiteColor];
            });
            
            
            
            
        } else {
            
            // 当本地有图片的时候优先加载
            // 将本地的图片数据转为图片
            iamge = [UIImage imageWithData:data];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.image = iamge;
//                self.cell.label2.textColor = [UIColor whiteColor];
            });
            
            
            
            
        }
        
        
        
        
        
        
        
        
        
        
        
    }) ;
    
    
    
}



@end
